import React, {useEffect, useRef, useState} from 'react';
import MySurfacePlotTop from "../../component/MySurfacePlotTop/MySurfacePlotTop";
import style from './messageBoard.module.scss'
import LeaveMessage from "../../component/LeaveMessage/LeaveMessage";
import {Avatar, Button, Divider, message, Spin} from "antd";
import {store} from "../../store/store";
import {addMessage, getMessage} from "./MessageBoardApi";
import {UserOutlined} from "@ant-design/icons";
import {timestampToTime} from "../../utils/dateTimeUtlis";


//留言item
const MessageItems = (props) => {
    const LeaveMessageRef = useRef(null);
    const [messageList, setMessageList] = useState([])
    const [replyMessageId, setReplyMessageId] = useState(0)
    const imgUrl = props.item.userPhotoUrl

    //打开留言弹框
    const showModalLeaveMessage = (Id, name) => {
        if (Id) setReplyMessageId(Id)
        LeaveMessageRef.current.showModal(name);
    }

    //获取回复
    const getMessageListSon = () => {
        getMessage({searchData: {replyMessageId: props.item.id}}).then(res => {
            if (res.code === '200') {
                setMessageList(res.data.data)
            } else {
                message.error('获取留言失败')
            }
        }).catch(e => {
            message.error('获取留言失败')
        })
    }

    // 提交留言
    const submitMessageFun = (text) => {
        const reqData = {
            name: store.getState().UserRedux.user.userName,
            number: store.getState().UserRedux.user.userNumber,
            message: text,
            replyMessageId: replyMessageId
        }

        addMessage(reqData).then(res => {
            if (res.code === '200') {
                message.success('回复成功')
                props.fathergetMessageList()
                getMessageListSon()

            } else {
                message.error('回复失败')
            }
        }).catch(() => {
            message.error('回复失败')
        })
    }


    return (
        <div className={style.MessageItems}
             style={{border: props.item.replyMessageId === '0' ? '1px solid #F7F8F9' : ''}}>
            <div style={{display: "flex"}}>
                <div className={style.MessageItems_left}>
                    <div>
                        {imgUrl ? <Avatar src={imgUrl} shape="square" size={54} icon={<UserOutlined/>}/> :
                            <Avatar shape="square" size={54} icon={<UserOutlined/>}/>}
                    </div>
                </div>
                <div className={style.MessageItems_right}>
                    <div style={{display: "flex", marginTop: '5px'}}>
                        <div style={{color: '#26bbf1'}}>
                            {props.item.name}
                        </div>
                        <div style={{color: '#9FB6CA', marginLeft: '10px'}}>
                            <span>{timestampToTime(new Date(props.item.updatedAt).getTime())}</span>
                        </div>
                        <div style={{marginLeft: '10px', marginRight: '10px', cursor: "pointer", color: '#7C7979'}}
                             onClick={() => showModalLeaveMessage(props.item.id, props.item.name)}>回复
                        </div>
                    </div>
                    <div style={{marginTop: '10px'}}>{props.item.message}</div>
                    <div className={style.MessageItems_right_bottom}>
                        <div onClick={getMessageListSon} style={{cursor: "pointer", marginRight: '0.5rem'}}>
                            <i className="iconfont icon-pinglun-copy-copy"
                               style={{marginLeft: '10px', color: '#FFD666'}}></i>
                            <span>{props.item.replyTime}:查看回复</span>
                        </div>

                    </div>
                </div>
            </div>
            {/*回复*/}
            <div>
                {messageList.map((i) => {
                    return <MessageItems key={i.id}
                                         fathergetMessageList={getMessageListSon}
                                         item={i}></MessageItems>
                })}
            </div>
            <LeaveMessage ref={LeaveMessageRef} submitMessage={submitMessageFun}></LeaveMessage>

        </div>
    )
}

function MessageBoard() {
    const LeaveMessageRef = useRef(null);
    const [messageList, setMessageList] = useState([])
    const [spinState, setSpinState] = useState(false)
    const [listQuery, setListQuery] = useState({page: 1, limit: 10})

    //打开留言弹框
    const showModalLeaveMessage = (Id = undefined, name = undefined) => {
        LeaveMessageRef.current.showModal();
    }

    // 提交留言
    const submitMessageFun = (text) => {
        const reqData = {
            name: store.getState().UserRedux.user.userName,
            number: store.getState().UserRedux.user.userNumber,
            message: text,
            replyMessageId: 0
        }

        addMessage(reqData).then(res => {
            if (res.code === '200') {
                message.success('发表成功')
                getMessageFun()
            } else {
                message.error('发表失败')
            }
        }).catch(() => {
            message.error('发表失败')
        })
    }
    const getMore = () => {
        setListQuery({...listQuery, page: listQuery.page + 1})
    }

    //获取留言
    const getMessageFun = () => {
        setSpinState(true)
        const searchData = {replyMessageId: '0'}
        getMessage({searchData, listQuery}).then(res => {
            if (res.code === '200') {
                if (listQuery.page === 1) {
                    setMessageList(res.data.data)

                } else {
                    setMessageList([...messageList, ...res.data.data])
                }
            } else {
                message.error('获取留言失败')
            }
        }).catch(e => {
            message.error('获取留言失败')
        }).finally(() => {
            setSpinState(false)
        })
    }

    // 页面初始化
    useEffect(() => {
        getMessageFun()
    }, [listQuery])

    return (
        <div>
            <MySurfacePlotTop
                blogTitle='哥，咋地啊，不来说两句？来都来了，说两句嘛。'
                blogCoverTitle='每一次留言都是传递温暖的机会，用正能量点亮他人心灵。不要犹豫，积极留言，让世界因你而更美好！一起行动起来！'
                blogTypeState={false}
            >
            </MySurfacePlotTop>
            {/*留言内容*/}
            <div className={style.messageBoardContent}>
                <div className={style.messageBoardContent_left}>
                    {messageList.map((i) => {
                        return (
                            <div key={i.id}>
                                <MessageItems
                                    key={i.id}
                                    fathergetMessageList={getMessageFun}
                                    item={i}></MessageItems>
                                <Divider/>
                            </div>
                        )
                    })}
                    <div style={{textAlign: "center", fontSize: '0.7rem', color: '#26bbf1', marginTop: '1rem'}}>
                        <span style={{cursor: "pointer"}} onClick={getMore}>
                            {!spinState ? '获取更多' : <Spin/>}
                        </span>
                    </div>
                </div>
                <div className={style.messageBoardContent_right}>
                    <Button type="primary" style={{marginLeft: '10px', width: '100%', marginTop: '10px'}}
                            onClick={showModalLeaveMessage}>发表留言</Button>
                </div>
            </div>
            <LeaveMessage ref={LeaveMessageRef} submitMessage={submitMessageFun}></LeaveMessage>
        </div>
    );
}

export default MessageBoard;
